#!/bin/bash

main(){
  # 清理rbac授权
  clean_rbac
  # 部署NFS Provisioner
  nfs_provisioner_deploy
  # 创建 StorageClass
  create_storage_class
  # 创建pvc
  create_pvc
}


# 清理rbac授权
clean_rbac(){
kubectl delete -f nfs-rbac.yaml -n kube-system

# 编写yaml
cat >nfs-rbac.yaml<<-EOF
---
kind: ServiceAccount
apiVersion: v1
metadata:
  name: nfs-client-provisioner
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: nfs-client-provisioner-runner
rules:
  - apiGroups: [""]
    resources: ["persistentvolumes"]
    verbs: ["get", "list", "watch", "create", "delete"]
  - apiGroups: [""]
    resources: ["persistentvolumeclaims"]
    verbs: ["get", "list", "watch", "update"]
  - apiGroups: ["storage.k8s.io"]
    resources: ["storageclasses"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["events"]
    verbs: ["create", "update", "patch"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: run-nfs-client-provisioner
subjects:
  - kind: ServiceAccount
    name: nfs-client-provisioner
    namespace: kube-system
roleRef:
  kind: ClusterRole
  name: nfs-client-provisioner-runner
  apiGroup: rbac.authorization.k8s.io
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: leader-locking-nfs-client-provisioner
rules:
  - apiGroups: [""]
    resources: ["endpoints"]
    verbs: ["get", "list", "watch", "create", "update", "patch"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: leader-locking-nfs-client-provisioner
subjects:
  - kind: ServiceAccount
    name: nfs-client-provisioner
    # replace with namespace where provisioner is deployed
    namespace: kube-system
roleRef:
  kind: Role
  name: leader-locking-nfs-client-provisioner
  apiGroup: rbac.authorization.k8s.io
EOF

# 应用授权
kubectl apply -f nfs-rbac.yaml -n kube-system
}

# 部署NFS Provisioner
nfs_provisioner_deploy(){
# 清理NFS Provisioner资源
kubectl delete -f nfs-provisioner-deploy.yaml -n kube-system

export NFS_ADDRESS='172.16.24.220'
export NFS_DIR='/opt/efk'

# 编写deployment.yaml
cat >nfs-provisioner-deploy.yaml<<-EOF
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: nfs-client-provisioner
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nfs-client-provisioner
  strategy:
    type: Recreate  #---设置升级策略为删除再创建(默认为滚动更新)
  template:
    metadata:
      labels:
        app: nfs-client-provisioner
    spec:
      serviceAccountName: nfs-client-provisioner
      containers:
        - name: nfs-client-provisioner
          #---由于quay.io仓库国内被墙，所以替换成七牛云的仓库
          #image: quay-mirror.qiniu.com/external_storage/nfs-client-provisioner:latest
          image: registry.cn-hangzhou.aliyuncs.com/open-ali/nfs-client-provisioner:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
            - name: nfs-client-root
              mountPath: /persistentvolumes
          env:
            - name: PROVISIONER_NAME
              value: nfs-client  #---nfs-provisioner的名称，以后设置的storageclass要和这个保持一致
            - name: NFS_SERVER
              value: ${NFS_ADDRESS}  #---NFS服务器地址，和 valumes 保持一致
            - name: NFS_PATH
              value: ${NFS_DIR}  #---NFS服务器目录，和 valumes 保持一致
      volumes:
        - name: nfs-client-root
          nfs:
            server: ${NFS_ADDRESS}  #---NFS服务器地址
            path: ${NFS_DIR} #---NFS服务器目录
EOF

# 部署deployment.yaml
kubectl apply -f nfs-provisioner-deploy.yaml -n kube-system

# 查看创建的pod
kubectl get pod -o wide -n kube-system|grep nfs-client

# 查看pod日志
kubectl logs -f `kubectl get pod -o wide -n kube-system|grep nfs-client|awk '{print $1}'` -n kube-system
}

# 创建 StorageClass
create_storage_class(){
# 清理storageclass资源
kubectl delete -f nfs-storage.yaml

# 编写yaml
cat >nfs-storage.yaml<<-EOF
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: nfs-storage
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"  #---设置为默认的storageclass
provisioner: nfs-client  #---动态卷分配者名称，必须和上面创建的"PROVISIONER_NAME"变量中设置的Name一致
parameters:
  archiveOnDelete: "true"  #---设置为"false"时删除PVC不会保留数据,"true"则保留数据
mountOptions:
  - hard        #指定为硬挂载方式
  - nfsvers=4   #指定NFS版本，这个需要根据 NFS Server 版本号设置
EOF

#部署class.yaml
kubectl apply -f nfs-storage.yaml

#查看创建的storageclass(这里可以看到nfs-storage已经变为默认的storageclass了)
kubectl get sc

}

# 创建pvc
create_pvc(){
# 删除命令空间
kubectl delete ns logging

# 创建命名空间
kubectl create ns logging

# 清理pvc
kubectl delete -f es-pv-claim.yaml -n logging

# 编写yaml
cat >es-pv-claim.yaml<<EOF
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: es-pv-claim
  namespace: logging
spec:
  storageClassName: nfs-storage #---需要与上面创建的storageclass的名称一致
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 10Gi
EOF

# 编写yaml
cat >es-pv-claim.yaml<<EOF
apiVersion: v1
kind: PersistentVolume
metadata:
  name: es-pv
spec:
  accessModes:
   - ReadWriteMany
  capacity:
    storage: 2Gi
  nfs:
    path: /opt/efk
    server: 172.163.24.220
  persistentVolumeReclaimPolicy: Retain
  storageClassName: nfs-storage    #PV的storageClassName保持和StorageClass名称相同，均为es-data-db
  volumeMode: Filesystem
---
# Define a 'Persistent Volume Claim'(PVC) for Mysql Storage, dynamically provisioned by cluster
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: es-pv-claim # name of PVC essential for identifying the storage data
  namespace: logging
  labels:
    app: elasticsearch
spec:
  accessModes:
    - ReadWriteMany   #This specifies the mode of the claim that we are trying to create.
  resources:
    requests:
      storage: 2Gi    #This will tell kubernetes about the amount of space we are trying to claim.
EOF

#创建PVC
kubectl apply -f es-pv-claim -n logging

kubectl get pv

#然后，我们进入到NFS的export目录，可以看到对应该volume name的目录已经创建出来了。其中volume的名字是namespace，PVC name以及uuid的组合：

#注意，出现pvc在pending的原因可能为nfs-client-provisioner pod 出现了问题，删除重建的时候会出现镜像问题
}

# 创建测试pod
test_pod(){
# 清理资源
kubectl delete -f test-pod.yaml -n logging

# 编写yaml
cat > test-pod.yaml <<EOF
kind: Pod
apiVersion: v1
metadata:
  name: test-pod
  namespace: logging
spec:
  containers:
  - name: test-pod
    image: busybox:1.28
    imagePullPolicy: IfNotPresent
    command:
      - "/bin/sh"
    args:
      - "-c"
      - "touch /mnt/SUCCESS && exit 0 || exit 1"
    volumeMounts:
      - name: nfs-pvc
        mountPath: "/mnt"
  restartPolicy: "Never"
  volumes:
    - name: nfs-pvc
      persistentVolumeClaim:
        claimName: es-pv-claim
EOF

#创建pod
kubectl apply -f test-pod.yaml -n logging

#查看创建的pod
kubectl get pod -o wide -n logging
}